package com.pandora.loan.common.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * @author developer
 */
public class JsonUtil {

    public static String toString(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(obj);
        } catch (IOException e) {
            return "{}";
        }
    }

    public static JsonNode fromString(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readTree(jsonString);
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 转化JSON String为对象
     *
     * @param json
     * @param clz
     * @param <T>
     * @return
     */
    public static <T> T convertStringToBean(String json, Class<T> clz) {
        ObjectMapper mapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        try {
            return mapper.readValue(json, clz);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    public static <T> T convertStringToBean(String json, TypeReference<T> valueTypeRef) {
        ObjectMapper mapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        try {
            return mapper.readValue(json, valueTypeRef);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

}
